import { App } from "@/models/app";
import { Component } from "@/models/component";
import { Container } from "@/models/containers";


export type TComponentServices = ReturnType<typeof getServices>

export function getServices(app: App) {
    const mId2cpMap = new Map<string, Component>()

    for (const cp of iterComponent(app)) {
        mId2cpMap.set(cp.id, cp)
    }


    function getComponent(id: string) {
        const cp = mId2cpMap.get(id)
        if (!cp) {
            throw new Error(`not found Component[id:${id}]`);
        }

        return cp
    }

    function getApp() {
        return app
    }

    return {
        getComponent,
        getApp,
    }
}





export function* iterComponent(app: App) {
    const stack = [app] as Container[]

    while (stack.length > 0) {

        const target = stack.pop()!

        for (const c of target.children) {
            if ((c as Container).children) {
                stack.push(c as Container)
            }
            yield c
        }
    }

}